package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOFileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.collections.BagUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOFileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 生成静态文件上传到minIO中
     * @param apArticle
     * @param content
     */
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        //数据校验
        if (apArticle == null || StringUtils.isEmpty(content)) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //合成
        try {
            Template template = configuration.getTemplate("article.ftl");
            Map model = new HashMap();
            model.put("content", JSON.parseArray(content));
            StringWriter out = new StringWriter();
            template.process(model, out);
            //上传minion
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", UUID.randomUUID().toString() + ".html", in);
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
            //消息队列添加数据，使es保持数据同步
            createArticleESIndex(apArticle,content);
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }

    /**
     * 创建es索引
     * @param apArticle
     * @param content
     */
    private void createArticleESIndex(ApArticle apArticle, String content) {
        if (apArticle == null || StringUtils.isEmpty(content)){
            return;
        }
        //封装一个ES的VO，包含了content
        SearchArticleVo articleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,articleVo);
        articleVo.setContent(content);
        kafkaTemplate.send(ArticleConstants.ARTICLE_PUBLISH_TOPIC,JSON.toJSONString(articleVo));
    }
}
